// controllers/authController.js
const authService = require('../services/authService');
const menuService = require('../services/menuService');

const { validationResult } = require('express-validator');
const Role = require('../models/role');
const asyncHandler = require('../middlewares/asyncHandler'); 


/**
 * @description: 登录接口
 * @param {*} req 包含email和password的请求对象
 * @param {*} res 包含token的响应对象
 * @return {*}
 */
const loginController = async (req, res) => {
  
  try {
    const { email, password } = req.body;
    const result = await authService.login(email, password);
    
    if(result.code === 200){
       res.cookie('token', result.data, { httpOnly: true });
    }

    res.status(result.code).json(result);
    
  } catch (error) {
    // 4. 错误处理
    res.status(error.code).json(error);
  }
};

/**
 * @description: 注册admin用户接口
 * @param {*} req 包含email和password的请求对象
 * @param {*} res 包含token的响应对象
 * @return {*}
 */

const addAdminUserController = async (req, res) => {
  // 1. 验证输入参数
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  const findAdminRole = await Role.findOne({ isAdmin: true });
  if(findAdminRole){
      return res.status(201).json({ code: 201, message: '系统已存在默认管理员' });
  }
  try {
    // 2. 调用服务层处理业务逻辑
    const userData = req.body;
    const newUser = await authService.addAdminUser(userData);
    // 3. 返回标准化响应
    res.status(200).json({
      code: 200,
      data: newUser,
      message: '用户admin注册成功'
    });
  } catch (error) {
    // 4. 错误处理
    res.status(500).json({
      code: 500,
      message: error.message
    });
  }

}

/**
 * @description: 注册普通用户接口
 * @param {*} req 包含email和password的请求对象
 * @param {*} res 包含token的响应对象
 * @return {*}
 */

const addUserController = async (req, res) => {
  // 1. 验证输入参数
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }

  try {
    // 2. 调用服务层处理业务逻辑
    const userData = req.body;
    const newUser = await authService.addUser(userData);
    
    // 3. 返回标准化响应
    res.status(200).json({
      code: 200,
      data: newUser,
      message: '用户注册成功'
    });
  } catch (error) {
    // 4. 错误处理
    res.status(500).json({
      code: 500,
      message: error.message
    });
  }
}
/*
 * @description: 获取用户信息
 * 通过 header Authorization获取token，然后解码token获取用户id，再根据用户id获取用户信息
 * @param {*} req 包含用户id的请求对象
 * @return {*}
 */

const getUserInfo = async (req, res) => {
  const token = req.headers.authorization.split(' ')[1];
  const decodedToken = authService.decodeToken(token);
  const userId = decodedToken.userId;
  try {
    const user = await authService.getUserInfo(userId);
    res.status(200).json({
      code: 200,
      data: user,
      message: '获取用户信息成功'
    })
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: error
    })
  }
}

module.exports = {
  login: loginController,
  addUser: addUserController,
  addAdminUser:addAdminUserController,
  getUserInfo,
};
